package cn.stylefeng.guns.modular.robot.cmd.impl;

import cn.hutool.core.date.DateUtil;
import cn.stylefeng.guns.modular.robot.cmd.abs.AbstractCmd;
import cn.stylefeng.guns.modular.robot.entity.Group;
import cn.stylefeng.guns.modular.robot.entity.Order;
import cn.stylefeng.guns.modular.robot.entity.OrderBatch;
import cn.stylefeng.guns.modular.robot.entity.enums.GroupMode;
import cn.stylefeng.guns.modular.robot.entity.vo.resp.BatchInfo;
import cn.stylefeng.guns.modular.robot.service.GroupService;
import cn.stylefeng.guns.modular.robot.service.OrderBatchService;
import cn.stylefeng.guns.modular.robot.utils.RobotUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@Transactional
public class CmdZero extends AbstractCmd {

    @Resource
    private CmdPlus cmdPlus;
    @Resource
    private GroupService groupService;
    @Resource
    private OrderBatchService orderBatchService;


    @Override
    public void exec(Update update, TelegramLongPollingBot bot) {
        String text = update.getMessage().getText();
        if (!getCmdName().equals(text) && !"+0".equals(text)) {
            return;
        }
        sendOrderInfo(update, bot);
    }

    public void sendOrderInfo(Update update, TelegramLongPollingBot bot) {
        Long chatId = update.getMessage().getChatId();
        Group group = groupService.getGroupByTgGroupId(chatId);
        List<OrderBatch> orderBatches = orderBatchService.lambdaQuery()
                .eq(OrderBatch::getBatchId, group.getBatchId())
                .list();
        OrderBatch orderBatch = orderBatches.get(0);
        BatchInfo batchInfo = cmdPlus.getBatchInfo(orderBatch);
        sendBiResultMsg(batchInfo, group, bot);
        sendUResultMsg(batchInfo, group, bot);
    }

    private void sendBiResultMsg(BatchInfo batchInfo, Group group, TelegramLongPollingBot bot) {
        if (GroupMode.USDT.equals(batchInfo.getGroupMode())) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        cmdPlus.getBiResultString(sb, "入款", batchInfo.getInOrders(), batchInfo.getAllInOrders(), batchInfo);
        sb.append("\n");
        cmdPlus.getBiResultString(sb, "下发", batchInfo.getOutOrders(), batchInfo.getAllOutOrders(), batchInfo);
        sb.append("\n");
        sb.append("<b>总入款: </b>").append(String.format("%.0f", batchInfo.getSumInAmount())).append("\n");
        sb.append("<b>费率: </b>").append(String.format("%.2f", group.getRate().multiply(BigDecimal.valueOf(100)))).append("%\n");
        sb.append("<b>单笔: </b>").append(String.format("%.0f", group.getExtract() == null ? BigDecimal.ZERO : group.getExtract())).append("\n");
        sb.append("\n");
        sb.append("<b>应下发: </b>").append(String.format("%.0f", batchInfo.getNeedGive())).append("\n");
        sb.append("<b>总下发: </b>").append(String.format("%.0f", batchInfo.getSumOutAmount())).append("\n");
        sb.append("<b>剩余: </b>").append(String.format("%.0f", batchInfo.getNeedGive().subtract(batchInfo.getSumOutAmount()))).append("\n");
        Date batchStartTime = group.getBatchStartTime();
        long time = System.currentTimeMillis() - batchStartTime.getTime();
        sb.append("\n");
        sb.append("已工作").append(time / 1000 / 60).append("分钟");
        RobotUtils.sendText(group.getTgGroupId(), sb.toString(), bot);
    }

    private void sendUResultMsg(BatchInfo batchInfo, Group group, TelegramLongPollingBot bot) {
        if (GroupMode.币.equals(batchInfo.getGroupMode())) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("<b>").append("入款").append(": (").append(batchInfo.getAllInOrders().size()).append("笔)</b>\n");
        for (Order od : batchInfo.getInOrders()) {
            String clearText = Boolean.TRUE.equals(od.getIsDelete()) ? "（清理不入账）" : "";
            String userName = " ";
            if (Boolean.TRUE.equals(batchInfo.getShowOderUser())) {
                userName = " " + od.getMemo() + " ";
            }
            if (!Objects.isNull(od.getExtract()) && BigDecimal.ZERO.compareTo(od.getExtract()) != 0) {
                sb.append(od.getId()).append(userName).append(DateUtil.format(od.getCreateTime(), "HH:mm:ss "))
                        .append("<b>").append("(").append(String.format("%.0f", od.getAmount())).append("-").append(String.format("%.0f", od.getExtract())).append(") / ").append(String.format("%.0f", od.getExchangeRate())).append(" = ")
                        .append(String.format("%.0f", od.getAmount().subtract(od.getExtract()).divide(od.getExchangeRate(), 4, RoundingMode.HALF_UP))).append("U").append(clearText).append("</b>\n");
            } else {
                sb.append(od.getId()).append(userName).append(DateUtil.format(od.getCreateTime(), "HH:mm:ss "))
                        .append("<b>").append(String.format("%.0f", od.getAmount())).append(" / ").append(String.format("%.0f", od.getExchangeRate())).append(" = ")
                        .append(String.format("%.0f", od.getAmount().divide(od.getExchangeRate(), 4, RoundingMode.HALF_UP))).append("U").append(clearText).append("</b>\n");
            }
        }
        sb.append("\n");
        sb.append("<b>").append("下发").append(": (").append(batchInfo.getAllOutOrders().size()).append("笔)</b>\n");
        for (Order od : batchInfo.getOutOrders()) {
            String clearText = Boolean.TRUE.equals(od.getIsDelete()) ? "（清理不入账）" : "";
            String userName = " ";
            if (Boolean.TRUE.equals(batchInfo.getShowOderUser())) {
                userName = " " + od.getMemo() + " ";
            }
            sb.append(od.getId()).append(userName).append(DateUtil.format(od.getCreateTime(), "HH:mm:ss "))
                    .append("<b>").append(String.format("%.0f", od.getAmount().divide(od.getExchangeRate(), 4, RoundingMode.HALF_UP))).append("U(").append(String.format("%.0f", od.getAmount())).append(")").append(clearText).append("</b>\n");
        }
        sb.append("\n");
        sb.append("<b>总入款: </b>").append(String.format("%.0f", batchInfo.getSumInAmount())).append("\n");
        sb.append("<b>总入U数: </b>").append(String.format("%.0f", batchInfo.getSumInU())).append("\n");
        sb.append("\n");
        sb.append("<b>费率: </b>").append(String.format("%.2f", group.getRate().multiply(BigDecimal.valueOf(100)))).append("%\n");
        sb.append("<b>USD汇率: </b>").append(String.format("%.2f", group.getExchangeRate())).append("\n");
        sb.append("<b>单笔: </b>").append(String.format("%.0f", group.getExtract())).append("\n");
        sb.append("\n");
        sb.append("<b>应下发: </b>").append(String.format("%.0f", batchInfo.getNeedGive())).append(" USDT\n");
        sb.append("<b>总下发: </b>").append(String.format("%.0f", batchInfo.getSumOutAmount())).append(" USDT\n");
        sb.append("<b>剩余: </b>").append(String.format("%.0f", batchInfo.getNeedGive().subtract(batchInfo.getSumOutAmount()))).append(" USDT\n");
        Date batchStartTime = group.getBatchStartTime();
        long time = System.currentTimeMillis() - batchStartTime.getTime();
        sb.append("\n");
        sb.append("已工作").append(time / 1000 / 60).append("分钟");
        RobotUtils.sendText(group.getTgGroupId(), sb.toString(), bot);
    }

    @Override
    public String getCmdName() {
        return "0";
    }

    @Override
    public String getDescribe() {
        return "0                                查询当前批次账单\n";
    }
}
